package controllers.manage.product;

import controllers.BaseController;
import controllers.auth.Secure;
import enums.ProductStatus;
import helper.AliyunOssUploader;
import helper.GlobalConfig;
import models.constants.DeletedStatus;
import models.merchant.Merchant;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import play.modules.paginate.JPAExtPaginator;
import play.mvc.Controller;
import play.mvc.With;
import product.Product;
import product.type.ProductType;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品管理
 * Created by buhaoba on 2017/4/6.
 */
@With(BaseController.class)
public class ProductCtrl extends Controller {

    /**
     * 跳转到产品管理页面
     */
    public static void index(Integer pageNumber, String name, Long  productType) {
        Merchant merchant = Secure.getLoginUser().merchant;
        pageNumber = pageNumber == null ? 1 : pageNumber;
        List<ProductType> productTypeList=ProductType.findAllProductTypes();
        Map<String , Object> searchMap = new HashMap<>();
        if(StringUtils.isNotBlank(name)){
            searchMap.put("name", "%"+name+"%");
        }
        if(productType!=null){
            searchMap.put("productType", productType);
        }

//        if(merchant != null){
//            searchMap.put("merchantId", merchant.id);
//        }
//        flash.put("menuId", "14");

        JPAExtPaginator<Product> resultPage = Product.findByCondition(searchMap, "createAt desc", pageNumber, GlobalConfig.PAGE_SIZE);
            for(Product product:resultPage){
                if(product.productStatus== ProductStatus.UP){
                    product.status="上架";
                }else {
                    product.status="下架";
                }
            }
        render(resultPage, pageNumber,productTypeList,name,productType);
    }
    /**
     * 跳转到添加产品页面
     */
    public static void add() {
        List<ProductType> productTypes = ProductType.findAllProductTypes();
        Product product=new Product();
        product.merchantPrice=100.0;
        product.stock=100.0;
        product.unit="件";
        render(product,productTypes);
    }

    /**
     * 跳转到修改产品页面
     */
    public static void modify(long id, Integer pageNumber){
        List<ProductType> productTypes = ProductType.findAllProductTypes();
        Product product = Product.findById(id);
        render(product, pageNumber, productTypes);
    }

    /**
     * 创建产品
     * @param product
     */
    public static void create(Product product , File mainImage) {
        Merchant merchant = Secure.getLoginUser().merchant;
        product.merchant = merchant;
        Logger.info("create  mainImage : %s" , mainImage);
        try {
            if(mainImage != null) {
                BufferedImage sourceImg = ImageIO.read(new FileInputStream(mainImage));
                Integer width = sourceImg.getWidth();
                Integer height = sourceImg.getHeight();
                if(((double)width/(double)height) <1.2 || ((double)width/(double)height) > 1.4 ){
                    product.deleted = DeletedStatus.UN_DELETED;
                    product.save();
                    flash.put("msg" , "图片比例不是4:3");
                    modify(product.id, 1);
                }
                product.mainImage = AliyunOssUploader.uploadPublicFile(mainImage , 300);
            }
            if(product.stock == null){
                    product.stock=100.0;
            }
            if(product.merchantPrice == null ){
                    product.merchantPrice=0.0;
            }

            product.sellingPoint="由爱心超市提供";
            product.createdAt=new Date();
            product.deleted = DeletedStatus.UN_DELETED;
            product.save();
            flash.put("msg" , "产品创建成功");
            redirect("/BS0019/admin/product/index/1");
        } catch (Exception e) {
            Logger.warn(e, "LOG01750: product create failed!");
        }
    }

    /**
     * 修改产品
     */
    public static void update(Long id, Product product, Integer pageNumber,File mainImage){
        try {
            if(mainImage != null) {
                BufferedImage sourceImg = ImageIO.read(new FileInputStream(mainImage));
                Integer width = sourceImg.getWidth();
                Integer height = sourceImg.getHeight();
                if(((double)width/(double)height) <1.2 || ((double)width/(double)height) > 1.4 ){
                    Product.update(id , product);
                    flash.put("msg" , "图片比例不是4:3");
                    modify(id, pageNumber);
                }
                product.mainImage = AliyunOssUploader.uploadPublicFile(mainImage , 300);
            }
            if(product.stock == null){
                product.stock=100.0;
            }
            if(product.merchantPrice == null ){
                product.merchantPrice=0.0;
            }
            product.modifyAt=new Date();
            Product.update(id , product);
            flash.put("msg" , "产品修改成功");
            redirect("/BS0019/admin/product/index/"+pageNumber);
        } catch (Exception e) {
            Logger.warn(e, "LOG01750: product create failed!");
        }
    }

    /**
     * 删除产品
     */
    public static void delete(long id , Integer pageNumber){
        pageNumber = pageNumber == null ? 1 : pageNumber;
        Product product = Product.findById(id);
        product.deleted=DeletedStatus.DELETED;
        product.save();
        flash.put("msg" , "产品删除成功");
        redirect("/BS0019/admin/product/index/"+pageNumber);
    }
}
